package com.zsc.newbuds.service.impl;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import com.zsc.newbuds.consts.Consts;
import com.zsc.newbuds.entity.Admin;
import com.zsc.newbuds.entity.Record;
import com.zsc.newbuds.entity.Recycle;
import com.zsc.newbuds.entity.SaleRecord;
import com.zsc.newbuds.mapper.SaleRecordMapper;
import com.zsc.newbuds.service.SaleRecordService;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author D
 */
@Service
public class SaleRecordServiceImpl implements SaleRecordService {

    @Autowired
    SaleRecordMapper saleRecordMapper;

    @Autowired
    RedisUtil redisUtil;




    @Override
    public void setSaleRecord(Integer[] recordId) {
        System.out.println("测试这里");
        System.out.println(Arrays.toString(recordId));
        // TODO: 2021/4/5
        Consts consts = new Consts();
        Consts.recordIdList = consts.copyList;
        Consts.recordIdList = Arrays.asList(recordId);
    }

    @Override
    public List<SaleRecord> getSaleRecordList() {
        String key = "list:saleRecordList";
        List<SaleRecord> saleRecords = new ArrayList<> ();
        if(redisUtil.hasKey(key)){
            Map<Object, Object> map = redisUtil.hmget(key);
            for(Map.Entry<Object, Object> sale:map.entrySet()){
                saleRecords.add((SaleRecord)sale.getValue());
            }
        }else {
            Map< String,Object> map = new HashMap<>();
            saleRecords = saleRecordMapper.getSaleRecordList();
            for (SaleRecord saleRecord : saleRecords){
                map.put(saleRecord.getSaleId().toString(),saleRecord);
            }
            redisUtil.hmset(key,map);
        }
        return saleRecords;
    }

    @Override
    public void addSaleRecord(SaleRecord saleRecord,Integer[] recordId) {

        Consts consts = new Consts();
        Consts.recordIdList = consts.copyList;
        String recordKey = "list:recordList";
        String key = "list:saleRecordList";
        //已经出售的记录
        String soldKey = "list:soldList";
        String saleKey = "list:saleList";
        saleRecordMapper.addSaleRecord(saleRecord);
        redisUtil.hincr("totalAmount","1",saleRecord.getSaleMoney());
        redisUtil.hset(key,saleRecord.getSaleId().toString(),saleRecordMapper.getSaleRecordById(saleRecord.getSaleId()));
        for (Integer id : recordId){
            Record record = (Record)redisUtil.hget(saleKey,id.toString());
            redisUtil.hset(soldKey,id.toString(),record);
            redisUtil.hdel(saleKey,id.toString());
            redisUtil.hdel(recordKey,id.toString());
        }
    }
}
